package org.familysearch.fsapi.gwt.samples.client;

import org.familysearch.fsapi.gwt.common.client.entities.Person;
import org.familysearch.fsapi.gwt.common.client.entities.PersonInformation;
import org.familysearch.fsapi.gwt.samples.client.handlers.PersonReadHandler;
import org.familysearch.fsapi.gwt.services.client.PersonServiceProxy;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ReadPersonSample extends Composite {

	private static ReadPersonSample singleton;
    public static ReadPersonSample get()
    {
        if( singleton == null )
        {
            singleton = new ReadPersonSample();
        }
        return singleton;
    }
    
    // entities
    private Person person;
	
	// widgets
    private VerticalPanel panel;
    private Button button;
	private HTML html;
	private DialogBox dialogBox = new DialogBox();	
	
	public ReadPersonSample()
	{
		
		singleton = this;
		
		panel = new VerticalPanel();
		person = new Person();
		person.setId("KW3B-F1K");
		//TODO: add query parameters in the form of person attributes,
		// but for now the stub returns a canned Person
		
		button = new Button("Get sample person");
		button.addClickListener(new ClickListener()
		{
			public void onClick(Widget sender) {
				getPerson(person);
			}
		});
		
		panel.add(button);
		
	    // Create the dialog box
	    dialogBox.setAnimationEnabled(true);
	    Button closeButton = new Button("close");
	    VerticalPanel dialogVPanel = new VerticalPanel();
	    dialogVPanel.setWidth("100%");
	    dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
	    dialogVPanel.add(closeButton);

	    closeButton.addClickListener(new ClickListener() {
	      public void onClick(Widget sender) {
	        dialogBox.hide();
	      }
	    });

	    dialogBox.setWidget(dialogVPanel);
	    
		initWidget(panel);
		
		
	}
	
    public void getPerson(Person person)
    {
        PersonServiceProxy.get().getPerson(person, new PersonReadHandler());
    }

	public void showPerson(Person person) {
		
		// fetch the first name from the person
		PersonInformation info = person.getPersonInformation();
		String fName = "";
		if( info != null)
		{
			fName = info.getFirstName();
		}
		// draw person's first name in a panel
        dialogBox.center();
        dialogBox.setText(person.getFullText());
        dialogBox.show();
		
	}
	
	public void showError(String error)
	{
		html.setHTML(error);
	}
}
